package com.xiaoliang.servlet.cart;

import com.xiaoliang.entry.Product;
import com.xiaoliang.service.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @author XIAOLIANG
 * @ClassName AddCart.java
 * @Description TODO
 * @createTime 2021年02月26日 16:39:00
 */
//@WebServlet("/cart/addCart")
public class AddCart extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ProductServiceImpl productService = new ProductServiceImpl();
		Integer id = Integer.valueOf(req.getParameter("id"));

		HttpSession session = req.getSession();
		HashMap<Integer,Product> cart;

		if (session.getAttribute("cart")==null){
		  cart = new HashMap<Integer, Product>();
		}else {
			cart = (HashMap<Integer, Product>) session.getAttribute("cart");
		}

		Product product;

		if (cart.containsKey(id)){  //购物车中该商品已经存在
					product = cart.get(id);
					product.setAccount(product.getAccount()+1);  //数量加1
					session.setAttribute("msg",product.getName()+"商品已在购物车中 数量加1 !");
		}else {                 //该商品并不在购入车中
					product = productService.selectOneById(id);

					if (product!=null){
						product.setAccount(1);    //购物车中的数量设置为1

						cart.put(id,product);
						session.setAttribute("msg",product.getName()+"添加购物车成功!");

					}else {
						session.setAttribute("msg","添加购物车失败! 商品不存在!");
					}
		}

				session.setAttribute("cart",cart);   //将修改后的购物车数据 加入session 更新数据

					String queryString = (String) session.getAttribute("queryString"); //拿到上一次 访问 Productlist 页面的地址的请求参数 实现带参请求

		if (queryString.length()<=1){   //上一次 没有请求参数
			resp.sendRedirect(req.getContextPath()+"/product/productList");
		}else {
			resp.sendRedirect(req.getContextPath()+"/product/queryList?"+queryString);
		}



			}
		}




